package com.dhecp.core.layui;

import com.dhecp.common.utils.TypeUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.framework.web.service.BaseInfoSimpleService;
import com.dhecp.project.base.domain.BaseInfo;
import com.dhecp.project.system.domain.SysDictionaryForModule;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.domain.SysSetting;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysDictionaryForModuleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class GridColumnsPropertyModel {
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private SysDictionaryForModuleService dictionaryForModuleService;
	
	@Autowired
	private BaseInfoSimpleService baseInfoSimpleService;
    /**
     * 返回列表各列及属性（如：列名、宽度）
     * @param moduleTable 必要参数：生成表格gridColumns对应的功能唯一值，用于获取设置的列属性。
     * @param entity 必要参数：生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
     * @param checkBox 可选参数：默认值checkBox="no"（不含复选框的表格），checkBox="yes"（含复选框的表格）
     * @param radio 可选参数：默认值radio="no"（不含单选框的表格），radio="yes"（含单选框的表格）
     * @param toolBarWidth 可选参数：操作区宽度，默认200（示例：params.put("toolBarWidth", "100");）,0表示无操作区
     * @param readOnly 可选参数：默认值 true（只读表格），false（可编辑的表格）
     * @param hiddenFieldsMap 可选参数：指定需要隐藏的字段
     * @param getFieldAttributesType 可选参数：页面类型（page：查询页网格[默认]，pagecallin：调入页网格，pageingrid：制单页网格）
     * @return Map : totalRow 是否含列合计，gridBody 表格主体，decimalList 数值类型字段， fieldRequiredList 必填字段， fieldNameRequiredList 必填字段中文名称， gridNewLine 表格新增行模板列
     * @author DH-Xxj
     */
    @SuppressWarnings("unchecked")
	public Map<String, Object> queryGridColumnsPropertyModel(Map<String, Object> params){
    	String toolBarWidth = "200"; //列宽
    	String moduleTable = "moduleTable";
    	String moduleName = "未知功能";
        String moduleAlias = "未知功能";
    	Boolean totalRow = false; //是否生成合计列
    	Boolean readOnly = true;  //是否为只读表格
    	Map<String, String> hiddenFieldsMap = new HashMap<String, String>();
    	if (params.get("checkBox") == null || params.get("checkBox") == ""){	//是否含复选框，默认不含
    		params.put("checkBox", "no");
    	}
    	if (params.get("radio") == null || params.get("radio") == ""){	//是否含单选框，默认不含
    		params.put("radio", "no");
    	}
    	if (params.get("toolBarWidth") != null && params.get("toolBarWidth") != ""){	//操作区宽度
    		toolBarWidth = params.get("toolBarWidth").toString();
    	}
    	if (params.get("readOnly") != null && !(Boolean)params.get("readOnly")){	//是否为只读表格，默认为是
    		readOnly = (Boolean)params.get("readOnly");
    	} 
    	if (params.get("entity") == null || params.get("entity") == ""){
    		params.put("entity", new SysDictionaryForPageField());
    	}
    	if (params.get("moduleTable") != null && params.get("moduleTable") != ""){
    		moduleTable = params.get("moduleTable").toString();
        	SysDictionaryForModule dictionaryForModule = new SysDictionaryForModule();
        	dictionaryForModule = dictionaryForModuleService.queryDictionaryForModuleByModuleTable(moduleTable);
        	if (dictionaryForModule != null){
            	moduleName = ((dictionaryForModule.getModuleName() == null || "".equals(dictionaryForModule.getModuleName())) ? "未知功能" : dictionaryForModule.getModuleName());
            	moduleAlias = ((dictionaryForModule.getModuleAlias() == null || "".equals(dictionaryForModule.getModuleAlias())) ? moduleName : dictionaryForModule.getModuleAlias());
            }
    	}
    	if (params.get("hiddenFieldsMap") == null || params.get("hiddenFieldsMap") == ""){	//指定需要隐藏的字段
    		hiddenFieldsMap = null;
    	}else{
    		hiddenFieldsMap = (Map<String, String>) params.get("hiddenFieldsMap");
    	}
    	if (params.get("getFieldAttributesType") == null || params.get("getFieldAttributesType") == ""){	//页面类型
    		params.put("getFieldAttributesType", "page");
    	}

    	List<SysDictionaryForPageField> dictionaryForPageFieldList = new ArrayList<SysDictionaryForPageField>();//表格字段属性
    	List<Map<String, Object>> finalDictionaryForPageFieldList = new ArrayList<Map<String, Object>>();//最终表格字段属性（添加额外属性）
    	List<String> decimalList = new ArrayList<String>();				//数值类型的字段
    	List<String> fieldRequiredList = new ArrayList<String>();		//必填字段
    	List<String> fieldNameRequiredList = new ArrayList<String>();	//必填字段中文名称
        List<Object> gridBodyList = new ArrayList<Object>();			//表格主体
        Map<String, Object> gridNewLine = new HashMap<String, Object>();//表格新增行模板列
        Map<String, Object> gridColumns = new HashMap<String, Object>();
        Map<String, Object> gridColumnLeft = new HashMap<String, Object>();
        Map<String, Object> gridColumnCheckBox = new HashMap<String, Object>();
        Map<String, Object> gridColumnRight = new HashMap<String, Object>();
        Map<String, Object> decimalMap = new HashMap<String, Object>();	//数值类型小数位数
        SysSetting sysSetting = ShiroUtils.getSystemSet();					//系统设置信息
        
        Integer decimalForPrice = sysSetting.getDecimalForPrice();		//价格小数位数
        Integer decimalForSum = sysSetting.getDecimalForSum();			//金额小数位数
        Integer decimalForNumber = sysSetting.getDecimalForNumber();		//数量小数位数
        Integer decimalForPercent = sysSetting.getDecimalForPercent();	//百分比小数位数
        
        gridColumnLeft.put("type", "numbers");
        gridColumnLeft.put("fixed", "left");
        gridColumnLeft.put("width", "45");//默认宽度给四十五，以满足三位数显示，否则layui默认给40只能显示两位数
        gridBodyList.add(TypeUtils.mapToJson(gridColumnLeft));

        if ("yes".equals(params.get("checkBox").toString().toLowerCase())){	//添加复选框
        	gridColumnCheckBox.put("type", "checkbox");
        	gridColumnCheckBox.put("fixed", "left");
        	gridBodyList.add(TypeUtils.mapToJson(gridColumnCheckBox));
        }
        if ("yes".equals(params.get("radio").toString().toLowerCase())){	//添加单选框
        	gridColumnCheckBox.put("type", "radio");
        	gridColumnCheckBox.put("fixed", "left");
        	gridBodyList.add(TypeUtils.mapToJson(gridColumnCheckBox));
        }
        
        if (params.get("moduleTable") != null && params.get("moduleTable") != ""){
            try{
            	params.put("Stringent", false); //查询字典时不按实体转换字段大小写（在后续循环中转换）
            	Map<String, Object> entityFieldMap = TypeUtils.entityFieldsToMap(params.get("entity"));
            	dictionaryForPageFieldList = dictionaryForFieldService.queryFieldAttributesList(params);
                for (SysDictionaryForPageField dicFields : dictionaryForPageFieldList){
                	if (readOnly){	//只读表格把字段属性设置为不可编辑
                		dicFields.setFieldFrontEdit(false);
                	}
                	
                    String field = ""; 
                    //字段大小写以实体为标准进行转换
                    if (dicFields.getFields() == null){
                    	field = "nofield";
                    }else if (entityFieldMap.get(dicFields.getFields().toLowerCase()) != null && !"".equals(entityFieldMap.get(dicFields.getFields().toLowerCase()))){
                    	field = entityFieldMap.get(dicFields.getFields().toLowerCase()).toString();
                    }else{
                    	field = dicFields.getFields();
                    }
                	dicFields.setFields(field);
                    if (dicFields.getFieldMatched() != null && entityFieldMap.get(dicFields.getFieldMatched().toLowerCase()) != null && !"".equals(entityFieldMap.get(dicFields.getFieldMatched().toLowerCase()))){
                    	dicFields.setFieldMatched(entityFieldMap.get(dicFields.getFieldMatched().toLowerCase()).toString());
                    }
                    //添加必填字段数组
            		if (dicFields.getFieldFrontRequired() != null && dicFields.getFieldFrontRequired()){
            			fieldRequiredList.add(field); //必填字段数组
            			fieldNameRequiredList.add(dicFields.getFieldName());//必填字段中文名称数组
            		}
                    
//                    if (dicFields.getFieldFrontHidden() != null && !dicFields.getFieldFrontHidden()){  
                    if (dicFields.getFieldFrontHidden() != null){
                    	if ("int".equals(dicFields.getFieldType()) || dicFields.getFieldType().indexOf("decimal") != -1){
                    		decimalList.add(field); //添加数值类型字段
                    		if ("t_price".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, decimalForPrice);
                    		}else if ("t_sum".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, decimalForSum);
                    		}else if ("t_number".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, decimalForNumber);
                    		}else if ("t_percent".equals(dicFields.getFieldFrontTemplet().toString()) || "p_percent".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, decimalForPercent);
                    		}else if ("t_appoint1".equals(dicFields.getFieldFrontTemplet().toString()) || "p_appoint1".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, 1);
                    		}else if ("t_appoint2".equals(dicFields.getFieldFrontTemplet().toString()) || "p_appoint2".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, 2);
                    		}else if ("t_appoint3".equals(dicFields.getFieldFrontTemplet().toString()) || "p_appoint3".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, 3);
                    		}else if ("t_appoint4".equals(dicFields.getFieldFrontTemplet().toString()) || "p_appoint4".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, 4);
                    		}else if ("t_appoint5".equals(dicFields.getFieldFrontTemplet().toString()) || "p_appoint5".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, 5);
                    		}else if ("t_appoint6".equals(dicFields.getFieldFrontTemplet().toString()) || "p_appoint6".equals(dicFields.getFieldFrontTemplet().toString())){
                    			decimalMap.put(field, 6);
                    		}else{
                    			decimalMap.put(field, 0);
                    		}
                    	}
                    	gridNewLine.put(field, dicFields.getFieldFrontValue()==null?"":dicFields.getFieldFrontValue()); //添加表格新增行模板列(取默认值)
                        Map<String, Object> gridBody = new HashMap<String, Object>(); 
                        String title = dicFields.getFieldName() == null ? "未知名称" : dicFields.getFieldName();
                        if (params.get("getFieldAttributesType") != null && "pageingrid".equals(params.get("getFieldAttributesType"))){
                        	if (dicFields.getFieldFrontRequired()){
                        		//制单页面网格中，必填字段前加上红色 * 符号
                        		title = "<font class=\"f_red\">*</font>" + title;
                        	}
                        }
                        gridBody.put("sort", "true"); //设置列排序功能
                        gridBody.put("field", field);
                        gridBody.put("title", title);
                        gridBody.put("align", dicFields.getFieldFrontAlign() == null ? "center" : dicFields.getFieldFrontAlign());
                        gridBody.put("width", dicFields.getFieldFrontWidth() == null ? 200 : dicFields.getFieldFrontWidth());
                        if (dicFields.getFieldFrontTotal() != null && dicFields.getFieldFrontTotal()){ //添加列合计
                        	gridBody.put("totalRow", true);
                            totalRow = true;
                        }
                        if (dicFields.getFieldFrontFixed() != null && dicFields.getFieldFrontFixed()){ //设置列固定
                        	gridBody.put("fixed", "left");
                        }
                        if (hiddenFieldsMap != null && hiddenFieldsMap.containsKey(dicFields.getFields().toString().toLowerCase())){ //指定需要隐藏的字段
                        	gridBody.put("hide", "true");
                        }
                        if ("guid".equals(dicFields.getFields().toString().toLowerCase())){	//隐藏GUID列
                        	gridBody.put("hide", "true");
                        }
                        if (dicFields.getFieldFrontWidth() != null && dicFields.getFieldFrontWidth() == 0){ //隐藏宽度设置为0的列
                        	gridBody.put("hide", "true");
                        }
                        if (dicFields.getFieldFrontTop() != null && dicFields.getFieldFrontTop() == 7){ //FieldFrontTop为7时隐藏
                        	gridBody.put("hide", "true");
                        }
                        if (!readOnly){ //非只读添加可编辑属性
                        	if (dicFields.getFieldFrontType() != null && dicFields.getFieldFrontEdit()){
                        		if ("t_buttontext".equals(dicFields.getFieldFrontType())){ //添加弹出框模板
                        			gridBody.put("templet", "#buttontext_"+field);
                        		}else if ("t_buttontextedit".equals(dicFields.getFieldFrontType())){ //添加可编辑弹出框模板
                        			gridBody.put("templet", "#buttontextedit_"+field);
                        		}else if ("t_dropdown".equals(dicFields.getFieldFrontType())){ //添加下拉框模板
                        			gridBody.put("templet", "#dropdown_" + field);
                        			gridBody.put("event", "select_" + field);
                        		}else if ("t_dropdownedit".equals(dicFields.getFieldFrontType())){ //添加可编辑下拉框模板
                        			gridBody.put("templet", "#dropdownedit_" + field);
                        			gridBody.put("event", "select_" + field);
                        		}else if ("t_file".equals(dicFields.getFieldFrontType())){ //添加附件模板
                        			gridBody.put("templet", "#file_" + field);
                        		}else if ("t_file2".equals(dicFields.getFieldFrontType())){ //添加照片附件模板
                        			gridBody.put("templet", "#file2_" + field);
                        		}else if ("t_radio".equals(dicFields.getFieldFrontType())){ //添加单选框模板
                        			gridBody.put("templet", "#radio_" + field);
                        		}else if ("t_checkbox".equals(dicFields.getFieldFrontType())){ //添加复选框模板
                        			gridBody.put("templet", "#checkbox_"+field);
                        		}else if ("t_date".equals(dicFields.getFieldFrontType())||"t_datetime".equals(dicFields.getFieldFrontType())){ //添加日期模板
                        			gridBody.put("templet", "#date_" + field);
                        		}else if ("t_decimal".equals(dicFields.getFieldFrontType())){ //添加数值型模板
                        			gridBody.put("templet", "#decimal_" + field);
                        			if (dicFields.getFieldFrontEdit()){
                                    	gridBody.put("edit", "text");
                            		}
                        		}else if ("t_textarea".equals(dicFields.getFieldFrontType())){	//添加文本域模板
                        			gridBody.put("templet", "#textarea_" + field);
                        		}else if (dicFields.getFieldFrontEdit()){
                                	gridBody.put("edit", "text");
                        		}
                        	}
                        }else{//只读页面（包括单据不可操作、查询列表页面）
                        	if ("t_file".equals(dicFields.getFieldFrontType())){ //添加附件模板
                    			gridBody.put("templet", "#file_" + field);
                        	}else if ("t_file2".equals(dicFields.getFieldFrontType())){ //添加照片附件模板
                        		gridBody.put("templet", "#file2_" + field);
                        	}else if ("t_textarea".equals(dicFields.getFieldFrontType())){ //添加文本域模板
                    			gridBody.put("templet", "#textarea_" + field);
                        	}else if ("t_checkbox".equals(dicFields.getFieldFrontType())){ //添加复选框模板
                    			gridBody.put("templet", "#checkbox_"+field);
                    		}else{
                            	gridBody.put("templet", "#templet_" + field);
                        	}
                        }
                    	gridBody.put("fieldMatched", dicFields.getFieldMatched());
                    	gridBody.put("fieldFrontSave", dicFields.getFieldFrontSave());
                    	gridBody.put("fieldFrontShow", dicFields.getFieldFrontShow());
                    	gridBody.put("fieldFrontType", dicFields.getFieldFrontType());
                        gridBodyList.add(TypeUtils.mapToJson(gridBody));
						
                		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                		if("mobile".equals(params.get("getFieldAttributesSystemType").toString())) {
                    		//如果有下拉控件，则根据配置获取对应下拉待选内容
                    		List<BaseInfo> dropdownList = new ArrayList<BaseInfo>();
                    		String fieldFrontType = dicFields.getFieldFrontType();
                    		String fieldSearchType = dicFields.getFieldSearchType();
                    		String fieldFrontSave = dicFields.getFieldFrontSave();
                    		String fieldFrontShow = dicFields.getFieldFrontShow();
                    		if (fieldFrontType != null && fieldFrontType.toLowerCase().startsWith("t_dropdown")){
                    			if (fieldSearchType != null && !"".equals(fieldSearchType)){
                    				if (fieldFrontSave == null || "".equals(fieldFrontSave)){
                    					fieldFrontSave = "vid";
                    				}
                    				if (fieldFrontShow == null || "".equals(fieldFrontShow)){
                    					fieldFrontShow = "vname";
                    				}
                    				dropdownList = baseInfoSimpleService.getDropdownData(fieldSearchType,fieldFrontSave,fieldFrontShow);
                    			}
                    		}
                    		fieldsListMap.put("dropdownList", dropdownList);
                		}
                		finalDictionaryForPageFieldList.add(fieldsListMap);
                    }
                }
            }catch(Exception e){
                System.out.println(e.getMessage().toString());
            }
        }
        if (!"0".equals(toolBarWidth)){	//添加操作区
            gridColumnRight.put("fixed", "right");
            gridColumnRight.put("title", "操作");
            gridColumnRight.put("align", "center");
            gridColumnRight.put("width", toolBarWidth);
            gridColumnRight.put("toolbar", "#barDh");
            gridBodyList.add(TypeUtils.mapToJson(gridColumnRight));
        }
        params.remove("Stringent");	//移除不按实体转换字段大小写的控制，防止影响后续查询
        params.remove("checkBox");  //移除生成复选框，防止影响后续查询
        params.remove("radio");     //移除生成单选框，防止影响后续查询
        params.remove("toolBarWidth");  //移除操作区宽度，防止影响后续查询
        
        gridColumns.put("moduleName", moduleName);
        gridColumns.put("moduleAlias", moduleAlias);
        gridColumns.put("moduleTable", moduleTable);			//对应功能唯一标识
        gridColumns.put("readOnly", readOnly);					//是否为只读表格
        gridColumns.put("totalRow", totalRow);					//是否含列合计
        gridColumns.put("gridBody", gridBodyList);				//表格主体
        gridColumns.put("dictionaryForPageFieldList", finalDictionaryForPageFieldList);//表格字段属性
        gridColumns.put("decimalList",decimalList);				//数值类型字段
        gridColumns.put("decimalObj", TypeUtils.mapToJson(decimalMap));//数值类型小数位数
        gridColumns.put("fieldRequiredList", fieldRequiredList); //必填字段
        gridColumns.put("fieldNameRequiredList", fieldNameRequiredList); //必填字段中文名称
        gridColumns.put("gridNewLine", gridNewLine); 			//表格新增行模板列
        
        return gridColumns;
    }
}
